<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登录 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body class="login-page">
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>用户登录</h2>

        <div class="card">
            <form th:action="@{/api/users/login}" method="post" id="loginForm" class="login-form">
                <div class="form-group">
                    <label for="username">用户名：</label>
                    <input type="text" id="username" name="username" required>
                </div>

                <div class="form-group">
                    <label for="password">密码：</label>
                    <input type="password" id="password" name="password" required>
                </div>

                <button type="submit" class="btn">登录</button>

                <div class="form-footer">
                    <p>还没有账号？<a th:href="@{/register}">立即注册</a></p>
                    <p>或者 <button type="button" id="guestLoginBtn" class="btn-link">以游客身份浏览</button></p>
                </div>
            </form>
        </div>

        <div id="msg"></div>
    </section>
</div>
<script>
    document.getElementById('loginForm').onsubmit = async function(e) {
        e.preventDefault();
        const form = e.target;

        try {
            const res = await fetch(form.action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({
                    username: form.username.value,
                    password: form.password.value
                })
            });

            const data = await res.json();

            if (data.error) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error}</div>`;
            } else {
                document.getElementById('msg').innerHTML = `<div class="success-msg">${data.msg || '登录成功'}</div>`;
                setTimeout(() => window.location.href = '/products', 1000);
            }
        } catch (error) {
            document.getElementById('msg').innerHTML = `<div class="error-msg">登录失败: ${error.message}</div>`;
        }
    };

    document.getElementById('guestLoginBtn').onclick = async function() {
        try {
            document.getElementById('msg').innerHTML = `<div class="info-msg">正在以游客身份登录...</div>`;

            const res = await fetch('/api/users/guest-login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include'
            });

            if (!res.ok) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">游客登录失败: 服务器返回 ${res.status} ${res.statusText}</div>`;
                return;
            }

            let data;
            try {
                data = await res.json();
            } catch (parseError) {
                console.error('解析响应失败:', parseError);
                const text = await res.text();
                document.getElementById('msg').innerHTML = `<div class="error-msg">游客登录失败: 无法解析响应 (${parseError.message})</div>`;
                console.error('原始响应:', text);
                return;
            }

            if (data.success) {
                document.getElementById('msg').innerHTML = `<div class="success-msg">${data.msg}</div>`;
                setTimeout(() => window.location.href = '/products', 1000);
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '游客登录失败'}</div>`;
            }
        } catch (error) {
            console.error('游客登录出错:', error);
            document.getElementById('msg').innerHTML = `<div class="error-msg">游客登录失败: ${error.message || '未知错误'}</div>`;
        }
    };
</script>
<style>
    .login-form {
        max-width: 400px;
        margin: 0 auto;
        padding: 20px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-footer {
        margin-top: 20px;
        text-align: center;
    }

    .form-footer a {
        color: var(--primary-color);
        text-decoration: none;
    }

    .form-footer a:hover {
        text-decoration: underline;
    }

    .btn-link {
        background: none;
        border: none;
        color: var(--primary-color);
        cursor: pointer;
        text-decoration: underline;
        padding: 0;
        font: inherit;
    }

    .btn-link:hover {
        color: var(--primary-dark);
    }

    .info-msg {
        background-color: #e3f2fd;
        border: 1px solid #bbdefb;
        color: #0d47a1;
        padding: 10px;
        margin: 10px 0;
        border-radius: 4px;
    }
</style>
</body>
</html>